package com.qiguliuxing.dts.db.util;


import cn.hutool.core.lang.Filter;
import cn.hutool.core.util.StrUtil;

/**
 * （自定义类描述）
 *
 * @author zhoujh
 * @date 2022/05/24 14:42
 */
public class SqlUtil {
    /**
     * sql特殊字符
     */
    private static final String SQL_SPECIAL_CHARACTER = "_%*@|&()[]\"'\\";
    public static String addSalashes(CharSequence content, Filter<Character> filter){
        if (StrUtil.isEmpty(content)) {
            return StrUtil.str(content);
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < content.length(); i++) {
            char c = content.charAt(i);
            if (filter.accept(c)) {
                sb.append('\\');
            }
            sb.append(c);
        }

        return sb.toString();
    }

    public static String addSalashes(CharSequence content, CharSequence applyCharacters){
        if (StrUtil.isEmpty(content)) {
            return StrUtil.str(content);
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < content.length(); i++) {
            char c = content.charAt(i);
            if (StrUtil.contains(applyCharacters, c)) {
                sb.append('\\');
            }
            sb.append(c);
        }

        return sb.toString();
    }

    public static String addSalashes(CharSequence content){
        if (StrUtil.isEmpty(content)) {
            return StrUtil.str(content);
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < content.length(); i++) {
            char c = content.charAt(i);
            if (StrUtil.contains(SQL_SPECIAL_CHARACTER, c)) {
                sb.append('\\');
            }
            sb.append(c);
        }

        return sb.toString();
    }

    public static String addSalashes(CharSequence content, char trimFix) {
        if (content.charAt(0) == trimFix) {
            content = content.subSequence(1, content.length());
        }
        if (content.charAt(content.length() - 1) == trimFix) {
            content = content.subSequence(0, content.length() - 1);
        }

        return addSalashes(content);
    }
}
